<template>
  <h1>商品详情</h1>

  <div>



    <div>
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="商品名称">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-col :span="11">
            <el-date-picker
                v-model="form.created_time"
                type="datetime"
                placeholder="请选择日期"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-col>
        </el-form-item>

          <el-form-item label="更显时间">
            <el-col :span="11">
              <el-date-picker
                  v-model="form.updated_time"
                  type="datetime"
                  placeholder="请选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-col>
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input v-model="form.sale" />
        </el-form-item>

        <el-form-item label="商品原价">
          <el-input v-model="form.price" />
        </el-form-item>

        <el-form-item label="商品描述">
          <el-input v-model="form.info" />
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="CartAdd">加入购物车</el-button>
          <el-button type="success" @click="myCart">我的购物车</el-button>
          <el-button @click="BackHome">返回首页</el-button>
        </el-form-item>
      </el-form>
    </div>








  </div>

</template>

<script lang="ts" setup>
import { useRoute ,useRouter} from 'vue-router'
import {ref, reactive, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import axios from "axios";

const router = useRouter()
const route = useRoute()
const imageUrl = ref('')
const id = route.query.id

function getData(){
  axios.get(`http://localhost:8000/api/goods/${id}/`).then(res => {
    console.log(res)
    form.name = res.data.name
    form.sale = res.data.sale
    form.price = res.data.price
    form.info = res.data.info
    form.created_time = res.data.created_time
    form.updated_time = res.data.updated_time
    imageUrl.value = res.data.image
  })
}



function handleAvatarSuccess(response,uploadFile){
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
function beforeAvatarUpload(rawFile){
  imageUrl.value = URL.createObjectURL(rawFile)
}

const form = reactive({
  name: '',
  sale: '',
  price: '',
  image: '',
  info: '',
  image_url:'',
  created_time:'',
  updated_time: ''
})


function BackHome(){
  router.push('/')
}


function CartAdd(){
  let token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token){
    alert('请先登录')
    router.push('/login')
  }

  if (token){
    const user_id = localStorage.getItem('user_id') || sessionStorage.getItem('user_id')
    if (user_id){
      axios.post(`http://localhost:8000/api/cartAdd/`,{
        goods_id: id,
      },{headers:{'Authorization':`Bearer ${token}`}}).then(res=>{
        if (res.data.code === 1){
          alert('加入购物车成功')
        }else {
          alert('加入购物车失败'||res.data.message)
        }
      }).catch(err=>{
        alert('加入购物车失败'||err)
      })
    }
  }

}


function myCart(){
  let token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token){
    alert('请先登录')
    router.push('/login')
    return
  }

  router.push('/cart')
}












onMounted(
    ()=>{
      getData()
    })


</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>